package com.yeziji.common.business.system.service.impl;

import com.yeziji.common.IServiceImpl;
import com.yeziji.common.business.system.constant.enums.SystemRoleTypeEnum;
import com.yeziji.common.business.system.dto.SystemRolePermissionDTO;
import com.yeziji.common.business.system.entity.SystemPermissionEntity;
import com.yeziji.common.business.system.entity.SystemRoleEntity;
import com.yeziji.common.business.system.entity.SystemRolePermissionRelationEntity;
import com.yeziji.common.business.system.mapper.SystemRolePermissionRelationMapper;
import com.yeziji.common.business.system.msg.SystemErrorMsg;
import com.yeziji.common.business.system.service.SystemPermissionService;
import com.yeziji.common.business.system.service.SystemRolePermissionRelationService;
import com.yeziji.common.business.system.service.SystemRoleService;
import com.yeziji.exception.ApiException;
import com.yeziji.utils.expansion.Asserts;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 系统角色权限关联表 服务层实现。
 *
 * @author system
 * @since 2023-11-13
 */
@Service
public class SystemRolePermissionRelationServiceImpl extends IServiceImpl<SystemRolePermissionRelationMapper, SystemRolePermissionRelationEntity> implements SystemRolePermissionRelationService {
    @Resource
    private SystemRoleService systemRoleService;
    @Resource
    private SystemPermissionService systemPermissionService;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean addRolePermission(SystemRolePermissionDTO systemRolePermissionDTO) {
        // 获取当前要绑定的权限
        Long permissionId = systemRolePermissionDTO.getPermissionId();
        SystemPermissionEntity permission =
                Asserts.notNull(
                        systemPermissionService.getById(permissionId),
                        SystemErrorMsg.SYSTEM_PERMISSION_IS_NOT_EXISTS
                );
        // 获取当前用户已有的权限, 如果角色不存在会自动创建[除了虚拟角色外]
        Long roleId = systemRolePermissionDTO.getRoleId();
        // refresh role
        if (roleId == null) {
            String roleName = systemRolePermissionDTO.getRoleName();
            SystemRoleEntity systemRoleEntity = systemRoleService.getRoleByType(SystemRoleTypeEnum.getByDesc(roleName));
            if (systemRoleEntity == null) {
                throw new ApiException(SystemErrorMsg.SYSTEM_ROLE_IS_EXISTS);
            }
            roleId = systemRoleEntity.getId();
        }
        // 保存角色与权限的关联关系
        return this.save(new SystemRolePermissionRelationEntity(roleId, permission.getId()));
    }

    @Override
    public boolean removeRolePermissionById(Long id) {
        SystemRolePermissionRelationEntity entity = super.getById(id, SystemErrorMsg.SYSTEM_ROLE_PERMISSION_IS_NOT_EXISTS);
        return this.removeById(entity.getId());
    }
}
